#include "page2.h"      // 点检看板
#include "ui_page2.h"
#include"qcustomplot/qcustomplot.h"
#include"src/mes.h"

Page2::Page2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Page2)
{
    ui->setupUi(this);
    ui->cycle->setStyleSheet("background:rgb(238,238,238);");
    ui->cycle->setReadOnly(true);
    ui->lockButton->setStyleSheet("background:rgb(238,238,238);");
    ui->label_2->setText(QDate::currentDate().toString("yyyy年MM月dd日ddd"));
    getMesCheckRecord();
    hour=int(ui->cycle->value());
    refreshTimer->start(hour*3600*1000);       //  消息提醒周期 1h
    connect(refreshTimer,SIGNAL(timeout()),this,SLOT(getMesCheckRecord()));
}

void Page2::getMesCheckRecord()         // 初始化图表
{
    if(Mes::getInstance()->getCheckRecord(noPassCheck,noPassReCheck,noPassMaintain,passCheck,
                        passReCheck,passMaintain,sumCheck,sumReCheck,sumMaintain)){
        initDraw();
    }
}

void Page2::initDraw()
{
    ui->customPlot->clearItems();
    ui->customPlot->clearGraphs();
    ui->customPlot->clearPlottables();
    // set dark background gradient: 设置背景
    QLinearGradient gradient(0, 0, 0, 400);
    gradient.setColorAt(0, QColor(90, 90, 90));
    gradient.setColorAt(0.38, QColor(105, 105, 105));
    gradient.setColorAt(1, QColor(70, 70, 70));
    ui->customPlot->setBackground(QBrush(gradient));
//    ui->customPlot->setBackground(QColor(255,255,255,0));      // 设置背景透明

//    ui->customPlot->plotLayout()->insertRow(0);              // 设置标题名称
//    m_title = new QCPTextElement(ui->customPlot,QString("宝德计算机%1").arg(QDate::currentDate().toString("yyyy-MM-dd")));
//    ui->customPlot->plotLayout()->addElement(0, 0, m_title);

    // create empty bar chart objects:
    noPassBar = new CustomBars(ui->customPlot->xAxis, ui->customPlot->yAxis);
    passBar = new CustomBars(ui->customPlot->xAxis, ui->customPlot->yAxis);
    sumBar = new CustomBars(ui->customPlot->xAxis, ui->customPlot->yAxis);
    QCPBarsGroup *group = new QCPBarsGroup(ui->customPlot);
    group->setSpacingType(QCPBarsGroup::stAbsolute);  // 设置组内柱状图的间距，按像素
    group->setSpacing(1);     // 设置较小的间距值，这样看起来更紧凑
    noPassBar->setBarsGroup(group);
    passBar->setBarsGroup(group);
    sumBar->setBarsGroup(group);
    QList<QCPBars*> bars;
    bars<<noPassBar<<passBar<<sumBar;
    foreach (QCPBars *bar, bars) {
      // 设置柱状图的宽度类型为以key坐标轴计算宽度的大小，其实默认就是这种方式
      bar->setWidthType(QCPBars::wtPlotCoords);
      bar->setWidth(bar->width() / bars.size()); // 设置柱状图的宽度大小
      group->append(bar);  // 将柱状图加入柱状图分组中
    }
//    //设置大小
//    noPassBar->setWidth(0.3);
//    passBar->setWidth(0.3);
//    sumBar->setWidth(0.3);
    //设置抗锯齿
    noPassBar->setAntialiased(false); // gives more crisp, pixel aligned bar borders
    passBar->setAntialiased(false);
    sumBar->setAntialiased(false);
// 	regen->setStackingGap(1);
// 	nuclear->setStackingGap(1);
// 	fossil->setStackingGap(1);

    // set names and colors:
    noPassBar->setName("异常数量");
    noPassBar->setPen(QPen(QColor(0, 168, 140).lighter(130)));
    noPassBar->setBrush(QColor(0, 168, 140));
    passBar->setName("今日已点检数量");
    passBar->setPen(QPen(QColor(250, 170, 20).lighter(150)));
    passBar->setBrush(QColor(250, 170, 20));
    sumBar->setName("今日需完成总数");
    sumBar->setPen(QPen(QColor(111, 9, 176).lighter(170)));
    sumBar->setBrush(QColor(111, 9, 176));

// 	// stack bars on top of each other:
// 	nuclear->moveAbove(fossil);
// 	regen->moveAbove(nuclear);

    // prepare x axis with country labels:
    QVector<double> ticks;
    QVector<QString> labels;
    ticks << 1 << 2 << 3;
    labels << "点检记录" << "校验记录" << "保养记录";
    QSharedPointer<QCPAxisTickerText> textTicker(new QCPAxisTickerText);
    textTicker->addTicks(ticks, labels);
    ui->customPlot->xAxis->setTicker(textTicker);
//    ui->customPlot->xAxis->setTickLabelRotation(60);
    ui->customPlot->xAxis->setSubTicks(false);
    ui->customPlot->xAxis->setTickLength(0, 4);
    ui->customPlot->xAxis->setRange(0,4);
    ui->customPlot->xAxis->setBasePen(QPen(Qt::white));
    ui->customPlot->xAxis->setTickPen(QPen(Qt::white));
    ui->customPlot->xAxis->grid()->setVisible(true);
    ui->customPlot->xAxis->grid()->setPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));
    ui->customPlot->xAxis->setTickLabelColor(Qt::white);
    ui->customPlot->xAxis->setLabelColor(Qt::white);

    // prepare y axis:
    ui->customPlot->yAxis->setRange(0, (sumCheck+10));
    ui->customPlot->yAxis->setPadding(5); // a bit more space to the left border
    ui->customPlot->yAxis->setLabel(QString("今日点检预览%1").arg(QDate::currentDate().toString("yyyy-MM-dd")));
    ui->customPlot->yAxis->setBasePen(QPen(Qt::white));
    ui->customPlot->yAxis->setTickPen(QPen(Qt::white));
    ui->customPlot->yAxis->setSubTickPen(QPen(Qt::white));
    ui->customPlot->yAxis->grid()->setSubGridVisible(true);
    ui->customPlot->yAxis->setTickLabelColor(Qt::white);
    ui->customPlot->yAxis->setLabelColor(Qt::white);
    ui->customPlot->yAxis->grid()->setPen(QPen(QColor(130, 130, 130), 0, Qt::SolidLine));
    ui->customPlot->yAxis->grid()->setSubGridPen(QPen(QColor(130, 130, 130), 0, Qt::DotLine));

    // Add data:
    QVector<double> fossilData, nuclearData, regenData;
    fossilData << noPassCheck << noPassReCheck << noPassMaintain;
    nuclearData << passCheck << passReCheck << passMaintain;
    regenData << sumCheck << sumReCheck << sumMaintain;
    noPassBar->setData(ticks, fossilData);
    passBar->setData(ticks, nuclearData);
    sumBar->setData(ticks, regenData);

    // setup legend:
    ui->customPlot->legend->setVisible(true);
    ui->customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop | Qt::AlignHCenter);
    ui->customPlot->legend->setBrush(QColor(255, 255, 255, 100));
    ui->customPlot->legend->setBorderPen(Qt::NoPen);
    QFont legendFont = font();
    legendFont.setPointSize(10);
    ui->customPlot->legend->setFont(legendFont);
    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);
}

Page2::~Page2()
{
    delete ui;
}

void Page2::on_lockButton_clicked()
{
    if(ui->lockButton->isChecked()){
        hour=int(ui->cycle->value());
        refreshTimer->start(hour*3600*1000);       //  消息提醒周期 1h
        connect(refreshTimer,SIGNAL(timeout()),this,SLOT(getMesCheckRecord()));
        ui->cycle->setStyleSheet("background:rgb(238,238,238);");
        ui->cycle->setReadOnly(true);
        ui->lockButton->setText("解锁");
        ui->lockButton->setStyleSheet("background:rgb(238,238,238);");
    }else{
        refreshTimer->stop();
        disconnect(refreshTimer,SIGNAL(timeout()),this,SLOT(getMesCheckRecord()));
        ui->cycle->setStyleSheet("background:rgb(198,225,248);");
        ui->cycle->setReadOnly(false);
        ui->lockButton->setText("锁定");
        ui->lockButton->setStyleSheet("background:rgb(198,225,248);");
    }
}

void Page2::on_refreshButton_clicked()      // 刷新
{
    getMesCheckRecord();
}


// 源文件CustomBars.cpp
CustomBars::CustomBars(QCPAxis *keyAxis, QCPAxis *valueAxis)
    : QCPBars(keyAxis, valueAxis),
    mTextAlignment(Qt::AlignCenter),
    mSpacing(5),
    mFont(QFont(QLatin1String("sans serif"), 12))
{

}

void CustomBars::setTextAlignment(Qt::Alignment alignment)
{
    mTextAlignment = alignment;
}

void CustomBars::setSpacing(double spacing)
{
    mSpacing = spacing;
}

void CustomBars::setFont(const QFont &font)
{
    mFont = font;
}
void CustomBars::draw(QCPPainter *painter)
{
    if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }
    if (mDataContainer->isEmpty()) return;

    QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;
    getVisibleDataBounds(visibleBegin, visibleEnd);

    // loop over and draw segments of unselected/selected data:
    QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;
    getDataSegments(selectedSegments, unselectedSegments);
    allSegments << unselectedSegments << selectedSegments;
    for (int i = 0; i < allSegments.size(); ++i)
    {
        bool isSelectedSegment = i >= unselectedSegments.size();
        QCPBarsDataContainer::const_iterator begin = visibleBegin;
        QCPBarsDataContainer::const_iterator end = visibleEnd;
        mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));
        if (begin == end)
            continue;

        for (QCPBarsDataContainer::const_iterator it = begin; it != end; ++it)
        {
            // draw bar:
            if (isSelectedSegment && mSelectionDecorator)
            {
                mSelectionDecorator->applyBrush(painter);
                mSelectionDecorator->applyPen(painter);
            }
            else
            {
                painter->setBrush(mBrush);
                painter->setPen(mPen);
            }
            applyDefaultAntialiasingHint(painter);
            QRectF barRect = getBarRect(it->key, it->value);   //自己加的
            painter->drawPolygon(barRect);
            // 以上是拷贝的源码部分
            painter->drawPolygon(barRect);

            // 我们仅需在 painter->drawPolygon(barRect); 这行下增加以下的内容即可

            // 计算文字的位置
            painter->setFont(mFont);                     // 设置字体
            QString text  = QString::number(it->value, 'g', 2);   // 取得当前value轴的值，保留两位精度
//            QString text=QString("%1").arg(it->value);

            QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, text);  // 计算文字所占用的大小

            if (mKeyAxis.data()->orientation() == Qt::Horizontal) {    // 当key轴为水平轴的时候
                if (mKeyAxis.data()->axisType() == QCPAxis::atTop)     // 上轴，移动文字到柱状图下面
                    textRect.moveTopLeft(barRect.bottomLeft() + QPointF(0, mSpacing));
                else                                                   // 下轴，移动文字到柱状图上面
                    textRect.moveBottomLeft(barRect.topLeft() - QPointF(0, mSpacing));
                textRect.setWidth(barRect.width());
                painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);
            }
            else {                                                  // 当key轴为竖直轴的时候
                if (mKeyAxis.data()->axisType() == QCPAxis::atLeft)   // 左轴，移动文字到柱状图右边
                    textRect.moveTopLeft(barRect.topRight() + QPointF(mSpacing, 0));
                else                                                  // 右轴，移动文字到柱状图左边
                    textRect.moveTopRight(barRect.topLeft() - QPointF(mSpacing, 0));
                textRect.setHeight(barRect.height());
                painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);
            }

        }
    }

}
